package edu.upc.dew.filter;

import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> additionalParams;
    private Map<String, String[]> allParams = null;

    public MyHttpServletRequestWrapper(HttpServletRequest req) {
        super(req);
    }

    public MyHttpServletRequestWrapper(HttpServletRequest req, Map<String, String[]> params) {
        super(req);
        additionalParams = new TreeMap<String, String[]>();
        additionalParams.putAll(params);
    }

    @Override
    public String getParameter(String name) {
        String[] params = (String[]) getParameterMap().get(name);
        if (null != params) {
            return params[0];
        }
        return null;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        if (null == allParams) {
            allParams = new TreeMap<String, String[]>();
            allParams.putAll(super.getParameterMap());
            allParams.putAll(additionalParams);
        }
        return Collections.unmodifiableMap(allParams);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return getParameterMap().get(name);
    }
}
